package com.hui.wanxin.web.service.impl;

import cn.hutool.http.HttpUtil;
import com.hui.wanxin.web.entity.User;
import com.hui.wanxin.web.entity.UserLogin;
import com.hui.wanxin.web.entity.wx.wxUserInfo;
import com.hui.wanxin.web.mapper.UserMapper;
import com.hui.wanxin.web.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.wanxin.web.utils.HttpUtils;
import com.hui.wanxin.web.utils.JwtUtils;
import com.hui.wanxin.web.utils.MyUtils;
import com.hui.wanxin.web.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 灰灰
 * @since 2023-10-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public R login(UserLogin userLogin) {
        //todo :等待 appId
        wxUserInfo wxUserInfo = HttpUtils.wxHttpUtils.getWxUserInfo("wx13a07840c2ae1e47","be1628d538e14b375e38e8c58a0f50ca",userLogin.getCode());

        if (wxUserInfo == null || wxUserInfo.getOpenid() == null) {
            throw new RuntimeException("登录失败");
        }
        User userInfo = lambdaQuery().eq(User::getOpenid, wxUserInfo.getOpenid()).one();

        if(userInfo == null){
            userInfo = new User();
            userInfo.setOpenid(wxUserInfo.getOpenid());
            save(userInfo);
        }

        String token = JwtUtils.geneJsonWebToken(userInfo);

        return R.success(token);
    }

    @Override
    public R bandPhone(UserLogin userLogin,String openId) {

        if(userLogin == null){
            return R.error("登录信息为空");
        }
        String phone = userLogin.getPhone();
        String code = redisTemplate.opsForValue().get("userLogin" + userLogin.getPhone());
        if(userLogin.getCode().equals(code)){
            User userInfo = lambdaQuery().eq(User::getOpenid,openId).one();
            userInfo.setPhone(phone);
            updateById(userInfo);

            return R.success();
        }else {
            return R.error("验证码错误");
        }
    }

    @Override
    public R realName(User user,String openId) {

        User userInfo = lambdaQuery().eq(User::getOpenid, openId).one();

        userInfo.setName(user.getName());
        userInfo.setSex(user.getSex());
        userInfo.setDiseaseType(user.getDiseaseType());
        return null;
    }


}
